#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>

#include "err_handle.h"
#include "cln_thread.h"
#include "clnt_socks.h"

int main(int argc, char *argv[])
{
    int sock_srv = 0;
    int sock_cln = 0;
    struct sockaddr_in serv_addr = {0};
    int rv = 0;
    int addr_opt = 1;
    pthread_t thread_id;

    if (argc != 2)
    {
        printf("usage: %s <port> . \n", argv[0]);
        return -1;
    }

    sock_srv = socket(PF_INET, SOCK_STREAM, 0);
    if (sock_srv == -1)
    {
        error_handling("socket() error .\n");
    }

    setsockopt(sock_srv, SOL_SOCKET, SO_REUSEADDR, (void *)&addr_opt, sizeof(addr_opt));
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(atoi(argv[1]));
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); //inet_addr("127.0.0.1")
    rv = bind(sock_srv, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if (rv != 0)
    {
        error_handling("bind() error .\n");
    }

    rv = listen(sock_srv, 5);
    if (rv != 0)
    {
        error_handling("listen() error .\n");
    }

    create_clnt_socks();
    while (1)
    {
        sock_cln = accept(sock_srv, NULL, NULL);
        if (sock_cln == -1)
        {
            error_handling("accept() error. \n");
        }
        add_clnt_sock(sock_cln);

        pthread_create(&thread_id, NULL, cln_thread, (void *)&sock_cln);
        pthread_detach(thread_id);
    }

    destroy_clnt_socks();
    close(sock_srv);
    return 0;
}